﻿using Microsoft.CodeAnalysis.CSharp.Scripting;
using NPOI.SS.Formula.Functions;
using System.Text;
using System.Text.RegularExpressions;
using ZXing.QrCode.Internal;

namespace CommandLib
{
    /// <summary>
    /// 动态代码执行类
    /// </summary>
    public sealed class DynamicRunCode
    {
        /// <summary>
        /// 动态执行代码，并反回结果
        /// </summary>
        /// <param name="code">动态编码</param>
        /// <returns></returns>
        public static object CodeRun(string code)
        {

            object result;
            try
            {
                result = CSharpScript.RunAsync(code).Result;
            }
            catch (Exception)
            {

                throw;
            }

            return result;

        }

        /// <summary>
        /// 动态表达式
        /// </summary>
        /// <param name="code">动态计算表达式</param>
        /// <returns></returns>
        public static object Evaluate(string code)
        {

            object result;
            try
            {
                result = CSharpScript.EvaluateAsync(code).Result;
            }
            catch (Exception)
            {

                throw;
            }

            return result;

        }
        /// <summary>
        /// 动态数据计算(四则运行)
        /// </summary>
        /// <param name="contxt"></param>
        /// <returns></returns>
        public static object Calculate(string contxt)
        {

            object result = null;
            string newtxt = "";
            try
            {
                var sb = new StringBuilder();
                if (!string.IsNullOrEmpty(contxt))
                {

                    newtxt = Regex.Replace(contxt, @"[+-]?\d*(,\d{3})*(\.\d+)?", "$0m",options: RegexOptions.Compiled);
                    newtxt = newtxt.Replace("[","(").Replace("]",")").Replace("{","(").Replace("}",")").Replace("mm","m");
                    newtxt = newtxt.Replace("m(", "(").Replace(")m",")");
                    result = CSharpScript.EvaluateAsync<decimal>(newtxt).Result;

                }

            }
            catch (Exception ex)
            {
                AsyncLoger.AddErrorLog(new { contxt,newtxt, ex });
            }
            return result;
        }
    }
}
